package com.situ.db;

import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class DBActivity extends AppCompatActivity implements
        View.OnClickListener {

    private MyOpenHelper myOpenHelper;

    private TextView mTvId;
    private EditText mEtName;
    private EditText mEtPhone;
    private Button mBtnAdd;
    private Button mBtnQuery;
    private Button mBtnUpdate;
    private Button mBtnDelete;

    private MyBaseAdapter mAdapter;
    private ListView mListView;
    // 当前点击的User，主要是用来做修改和删除
    private User mCurrentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myOpenHelper = new MyOpenHelper(getApplicationContext());
        init();//初始化控件
    }

    private void init() {
        mTvId = (TextView) findViewById(R.id.tv_id);
        mEtName = (EditText) findViewById(R.id.et_name);
        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mBtnAdd = (Button) findViewById(R.id.btn_add);
        mBtnQuery = (Button) findViewById(R.id.btn_query);
        mBtnUpdate = (Button) findViewById(R.id.btn_update);
        mBtnDelete = (Button) findViewById(R.id.btn_delete);
        mListView = (ListView) findViewById(R.id.listView);
        mBtnAdd.setOnClickListener(this);
        mBtnQuery.setOnClickListener(this);
        mBtnUpdate.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);


        SQLiteDatabase db = myOpenHelper.getReadableDatabase();

        Cursor cursor = db.rawQuery("select _id,name,phone from account", null);
        if (cursor.getCount() == 0) {
            Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
        }
        List<User> list = new ArrayList<>();
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {// 每遍历一次就是拿出这一行里面的数据
                int id = cursor.getInt(0);
                String n = cursor.getString(1);
                String p = cursor.getString(2);
                System.out.println("id: " + id + ", name: " + n + ", phone: " + p);
                User user = new User(id, n, p);
                list.add(user);
            }
        }
        db.close();
        cursor.close();

        //创建一个Adapter的实例
        mAdapter = new MyBaseAdapter(list);
        //设置Adapter
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        String name;
        String phone;
        SQLiteDatabase db;
        switch (v.getId()) {
            case R.id.btn_add: //添加数据
                db = myOpenHelper.getWritableDatabase();
                name = mEtName.getText().toString();
                phone = mEtPhone.getText().toString();
                db.execSQL("insert into account(name,phone) values(?,?)", new Object[]{name, phone});
                db.close();
                Toast.makeText(this, "信息已添加", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_query: //查询数据
                db = myOpenHelper.getReadableDatabase();

                Cursor cursor = db.rawQuery("select _id,name,phone from account", null);
                if (cursor.getCount() == 0) {
                    Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
                }
                List<User> list = new ArrayList<>();
                if (cursor != null && cursor.getCount() > 0) {
                    while (cursor.moveToNext()) {// 每遍历一次就是拿出这一行里面的数据
                        int id = cursor.getInt(0);
                        String n = cursor.getString(1);
                        String p = cursor.getString(2);
                        System.out.println("id: " + id + ", name: " + n + ", phone: " + p);
                        User user = new User(id, n, p);
                        list.add(user);
                    }
                }
                db.close();
                cursor.close();
                mAdapter.setList(list);
                mAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_update: //修改数据
                db = myOpenHelper.getWritableDatabase();
                name = mEtName.getText().toString();
                phone = mEtPhone.getText().toString();
                db.execSQL("update account set name=?,phone=? where _id=?", new Object[]{name, phone, mCurrentUser.getId()});
                Toast.makeText(this, "信息已修改", Toast.LENGTH_SHORT).show();
                db.close();
                break;
            case R.id.btn_delete: //删除数据
                db = myOpenHelper.getWritableDatabase();
                db.execSQL("delete from account where _id=?", new Object[]{mCurrentUser.getId()});
                Toast.makeText(this, "信息已删除", Toast.LENGTH_SHORT).show();
                db.close();
                break;
        }
    }

    class MyBaseAdapter extends BaseAdapter {
        private List<User> list = new ArrayList<>();

        public void setList(List<User> list) {
            this.list = list;
        }

        MyBaseAdapter(List<User> list) {
            this.list = list;
        }

        //得到item的总数
        @Override
        public int getCount() {
            //返回ListView Item条目的总数
            return list.size();
        }

        //得到Item代表的对象
        @Override
        public Object getItem(int position) {
            //返回ListView Item条目代表的对象
            return list.get(position);
        }

        //得到Item的id
        @Override
        public long getItemId(int position) {
            //返回ListView Item的id
            return position;
        }

        //得到Item的View视图
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            MyBaseAdapter.ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).
                        inflate(R.layout.list_db_item, parent, false);
                holder = new MyBaseAdapter.ViewHolder();
                holder.mTextView = (TextView) convertView.findViewById
                        (R.id.item_tv);
                convertView.setTag(holder);
            } else {
                holder = (MyBaseAdapter.ViewHolder) convertView.getTag();
            }
            holder.mTextView.setText(list.get(position).toString());

            // 添加点击事件
            convertView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mCurrentUser = list.get(position);
                    mTvId.setText(mCurrentUser.getId() + "");
                    mEtName.setText(mCurrentUser.getName());
                    mEtPhone.setText(mCurrentUser.getPhone());
                }
            });

            return convertView;
        }

        class ViewHolder {
            TextView mTextView;
        }
    }

}
